'use strick'

var NW = require('nw.gui'),
    logger = require('./../src/logger').getLogger('wechat_bot_qrcode.log'),
    net = require("net"),
    fs = require('fs');

const PROCESS_NAME = 'process2-';
const QRCodeImgDir = 'temp/loginQRcode.png';

global.process = process;

function init() {
    // 创建目录
    if (!fs.existsSync('temp')) {
        logger.info(PROCESS_NAME + "创建目录temp。")
        fs.mkdirSync('temp');
    }
    var out = fs.createWriteStream(QRCodeImgDir);
    out.on('err', function (err) {
        logger.info(err);
    })
    // 先打开窗口
    var client = net.connect({port: 8889},
        function () { //'connect' listener
            logger.info('connected to server!!!');
            /*client.write('world!\r\n');*/
        });
    client.on('data', function (data) {
        logger.info(data.byteLength + "----------" + typeof data);
        if (typeof data == "object") {
            out.write(data, () => {
                logger.info("传输完成");
                document.getElementById('qrcodeImg').src = QRCodeImgDir;
            })
        }
    });
    client.on('end', function () {
        logger.info('disconnected from server');
        window.close();
    });
    client.on('error', function (error) {
        logger.info("连接错误。");
        logger.info(error);
        window.close();
    });

    process.on('exit', (code) => {
        logger.info(PROCESS_NAME + `About to exit with code: ${code}`);
    });
}

logger.info(PROCESS_NAME + '子进程启动。');
init();
logger.info(PROCESS_NAME + '子进程结束。')